
package com.maggroup.conference_system.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.Predicate;

import org.springframework.data.jpa.domain.Specification;

/**
 * 查询条件的解析与获取
 *
 * @author peng
 */
public final class DynamicSpecifications {

    /**
     * 生成查询条件
     *
     * @param map
     * @param <T>
     * @return
     */
    public static <T> Specification<T> createSpecification(final Map<String, Object> map) {
    	
        return (root, query, cb) -> {
            List<Predicate> predicate = new ArrayList<>();
            map.forEach((key, val) -> {
            	try {
                    predicate.add(cb.equal(root.get(key).as(val.getClass()), val));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            Predicate[] pre = new Predicate[predicate.size()];
            return query.distinct(true).where(predicate.toArray(pre)).getRestriction();
        };
    }

}
